<template>
  <el-card class="stats-card">
    <template #header>
      <div class="card-header">
        <span>观影数据统计</span>
        <el-button type="primary" size="small" @click="refreshStats" :loading="loading">
          刷新
        </el-button>
      </div>
    </template>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="6" animated />
    </div>
    <div v-else-if="error" class="error-message">
      <el-alert
        title="获取数据失败"
        type="error"
        :description="error"
        show-icon
      />
    </div>
    <div v-else>
      <!-- 基本统计数据 -->
      <div class="stats-overview">
        <div class="stat-item">
          <div class="stat-label">总观影次数</div>
          <div class="stat-value">{{ stats.totalWatchCount || 0 }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">总消费金额</div>
          <div class="stat-value">¥{{ formatPrice(stats.totalSpent) }}</div>
        </div>
      </div>

      <!-- 电影类型分布 -->
      <div class="stats-section" v-if="hasGenreData">
        <h3>最常观看的电影类型</h3>
        <div class="genre-distribution">
          <div
            v-for="(count, genre) in stats.genreDistribution"
            :key="genre"
            class="genre-item"
          >
            <div class="genre-name">{{ genre }}</div>
            <div class="genre-bar-container">
              <div
                class="genre-bar"
                :style="{ width: calculateBarWidth(count, maxGenreCount) }"
              ></div>
              <span class="genre-count">{{ count }}次</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 观影时间分布 -->
      <div class="stats-section" v-if="hasTimeData">
        <h3>观影时间分布</h3>
        <div class="time-distribution">
          <div
            v-for="(count, month) in stats.watchTimeDistribution"
            :key="month"
            class="time-item"
          >
            <div class="time-month">{{ formatMonth(month) }}</div>
            <div class="time-bar-container">
              <div
                class="time-bar"
                :style="{ width: calculateBarWidth(count, maxTimeCount) }"
              ></div>
              <span class="time-count">{{ count }}次</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 最近观影记录 -->
      <div class="stats-section" v-if="hasRecentWatches">
        <h3>最近观影记录</h3>
        <el-table :data="stats.recentWatches" style="width: 100%">
          <el-table-column prop="movieTitle" label="电影" min-width="120" />
          <el-table-column prop="watchTime" label="观影时间" min-width="120" />
          <el-table-column prop="hallName" label="影厅" min-width="80" />
          <el-table-column prop="price" label="价格" min-width="80">
            <template #default="scope">
              ¥{{ formatPrice(scope.row.price) }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 无数据提示 -->
      <div v-if="!hasData" class="no-data">
        <el-empty description="暂无观影数据" />
      </div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { getUserMovieStats } from '../api/stats';
import { ElMessage, ElSkeleton, ElEmpty, ElAlert, ElTable, ElTableColumn } from 'element-plus';
import * as echarts from 'echarts';

// 定义统计数据类型
interface RecentWatchRecord {
  orderId: number;
  movieTitle: string;
  watchTime: string;
  hallName: string;
  price: number;
}

interface MovieStats {
  totalWatchCount: number;
  totalSpent: number;
  genreDistribution: Record<string, number>;
  watchTimeDistribution: Record<string, number>;
  recentWatches: RecentWatchRecord[];
}

// 初始化数据
const stats = ref<MovieStats>({
  totalWatchCount: 0,
  totalSpent: 0,
  genreDistribution: {},
  watchTimeDistribution: {},
  recentWatches: []
});
const loading = ref(true);
const error = ref<string | null>(null);

// 计算属性
const hasGenreData = computed(() => {
  return Object.keys(stats.value.genreDistribution || {}).length > 0;
});

const hasTimeData = computed(() => {
  return Object.keys(stats.value.watchTimeDistribution || {}).length > 0;
});

const hasRecentWatches = computed(() => {
  return (stats.value.recentWatches || []).length > 0;
});

const hasData = computed(() => {
  return stats.value.totalWatchCount > 0 || hasGenreData.value || hasTimeData.value || hasRecentWatches.value;
});

const maxGenreCount = computed(() => {
  if (!hasGenreData.value) return 0;
  return Math.max(...Object.values(stats.value.genreDistribution));
});

const maxTimeCount = computed(() => {
  if (!hasTimeData.value) return 0;
  return Math.max(...Object.values(stats.value.watchTimeDistribution));
});

// 方法
const refreshStats = async () => {
  loading.value = true;
  error.value = null;

  try {
    const data = await getUserMovieStats();
    stats.value = data;
  } catch (err: any) {
    console.error('获取观影统计数据失败:', err);
    error.value = err.response?.data?.message || '获取数据失败，请稍后再试';
  } finally {
    loading.value = false;
  }
};

const formatPrice = (price: number | null | undefined) => {
  if (price === null || price === undefined) return '0.00';
  return price.toFixed(2);
};

const formatMonth = (monthStr: string) => {
  // 将 "2023-05" 格式转换为 "2023年5月"
  const parts = monthStr.split('-');
  if (parts.length === 2) {
    return `${parts[0]}年${parseInt(parts[1])}月`;
  }
  return monthStr;
};

const calculateBarWidth = (count: number, maxCount: number) => {
  if (maxCount === 0) return '0%';
  // 最大宽度为80%，确保即使只有一个数据也有一定宽度
  const minWidth = 20;
  const maxWidth = 80;
  const percentage = (count / maxCount) * (maxWidth - minWidth) + minWidth;
  return `${percentage}%`;
};

// 组件挂载时获取数据
onMounted(refreshStats);
</script>

<style scoped>
.stats-card {
  margin-bottom: 30px;
  background-color: rgba(255, 255, 255, 0.85);
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  padding: 20px 0;
}

.error-message {
  margin: 20px 0;
}

.stats-overview {
  display: flex;
  justify-content: space-around;
  margin-bottom: 30px;
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 16px;
  color: #666;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
}

.stats-section {
  margin-bottom: 30px;
}

.stats-section h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.genre-distribution, .time-distribution {
  padding: 0 10px;
}

.genre-item, .time-item {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.genre-name, .time-month {
  width: 100px;
  font-size: 14px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.genre-bar-container, .time-bar-container {
  flex: 1;
  display: flex;
  align-items: center;
  height: 24px;
}

.genre-bar, .time-bar {
  height: 16px;
  background-color: #409EFF;
  border-radius: 4px;
  transition: width 0.5s ease;
}

.genre-count, .time-count {
  margin-left: 10px;
  font-size: 14px;
  color: #666;
}

.no-data {
  padding: 30px 0;
  text-align: center;
}
</style>
